import axios from 'axios';
import env from '../../build/env';
import semver from 'semver';
import packjson from '../../package.json';

let util = {

};
util.title = function (title) {
    title = title || '伊娃网站后台';
    window.document.title = title;
};

const ajaxUrl = env === 'development' ?
    'http://127.0.0.1:8888' :
    env === 'production' ?
    'https://www.url.com' :
    'https://debug.url.com';

util.ajax = axios.create({
    baseURL: ajaxUrl,
    timeout: 30000
});

util.inOf = function (arr, targetArr) {
    let res = true;
    arr.forEach(item => {
        if (targetArr.indexOf(item) < 0) {
            res = false;
        }
    });
    return res;
};

util.oneOf = function (ele, targetArr) {
    if (targetArr.indexOf(ele) >= 0) {
        return true;
    } else {
        return false;
    }
};

util.showThisRoute = function (itAccess, currentAccess) {
    if (typeof itAccess === 'object' && Array.isArray(itAccess)) {
        return util.oneOf(currentAccess, itAccess);
    } else {
        return itAccess === currentAccess;
    }
};

util.getRouterObjByName = function (routers, name) {
    if (!name || !routers || !routers.length) {
        return null;
    }
    // debugger;
    let routerObj = null;
    for (let item of routers) {
        if (item.name === name) {
            return item;
        }
        routerObj = util.getRouterObjByName(item.children, name);
        if (routerObj) {
            return routerObj;
        }
    }
    return null;
};

util.handleTitle = function (vm, item) {
    if (typeof item.title === 'object') {
        return vm.$t(item.title.i18n);
    } else {
        return item.title;
    }
};

util.setCurrentPath = function (vm, name) {
    let title = '';
    let isOtherRouter = false;
    vm.$store.state.app.routers.forEach(item => {
        if (item.children.length === 1) {
            if (item.children[0].name === name) {
                title = util.handleTitle(vm, item);
                if (item.name === 'otherRouter') {
                    isOtherRouter = true;
                }
            }
        } else {
            item.children.forEach(child => {
                if (child.name === name) {
                    title = util.handleTitle(vm, child);
                    if (item.name === 'otherRouter') {
                        isOtherRouter = true;
                    }
                }
            });
        }
    });
    let currentPathArr = [];
    if (name === 'home_index') {
        currentPathArr = [{
            title: util.handleTitle(vm, util.getRouterObjByName(vm.$store.state.app.routers, 'home_index')),
            path: '',
            name: 'home_index'
        }];
    } else if ((name.indexOf('_index') >= 0 || isOtherRouter) && name !== 'home_index') {
        currentPathArr = [{
                title: util.handleTitle(vm, util.getRouterObjByName(vm.$store.state.app.routers, 'home_index')),
                path: '/home',
                name: 'home_index'
            },
            {
                title: title,
                path: '',
                name: name
            }
        ];
    } else {
        function searchChild(item) {
            if (!item.children) {
                return item.name === name;
            } else if (item.children.length <= 1) {
                if (item.children[0]) {
                    return item.children[0].name === name || item.name === name;
                } else {
                    return item.name === name;
                }
            } else {
                let find = false;
                for (var i = 0; i < item.children.length; i++) {
                    find = searchChild(item.children[i]);
                    if (find) {
                        return true;
                    }
                }
                return false;
            }
        }
        let currentPathObj = vm.$store.state.app.routers.filter(searchChild)[0];

        currentPathArr.push({
            title: '首页',
            path: '',
            name: 'home_index'
        });

        addPath(vm.$store.state.app.routers, '');

        function addPath(routers, parentPath, onlyChild) {
            let route;
            if (onlyChild) {
                route = routers[0];
            } else {
                route = routers.filter(searchChild)[0];
            }
            if (route.meta === undefined) {
                return;
            }
            if (route.meta.type == 'dir') {
                currentPathArr.push({
                    title: route.title,
                    path: '',
                    name: route.name
                });
                if (route.children.length == 1) {
                    addPath(route.children, parentPath + route.path, true);
                } else {
                    addPath(route.children, parentPath + route.path);
                }
            } else {
                let path = parentPath + route.path;
                currentPathArr.push({
                    title: route.title,
                    path: path,
                    name: route.name
                });
            }
        }
    }
    vm.$store.commit('setCurrentPath', currentPathArr);

    return currentPathArr;
};

util.openNewPage = function (vm, name, argu, query) {
    if (!vm.$store) {
        return;
    }
    let pageOpenedList = vm.$store.state.app.pageOpenedList;
    let openedPageLen = pageOpenedList.length;
    let i = 0;
    let tagHasOpened = false;
    while (i < openedPageLen) {
        if (name === pageOpenedList[i].name) { // 页面已经打开
            vm.$store.commit('pageOpenedList', {
                index: i,
                argu: argu,
                query: query
            });
            tagHasOpened = true;
            break;
        }
        i++;
    }
    if (!tagHasOpened) {
        function searchTag(tagsList) {
            let tag = false;
            for (var i = 0; i < tagsList.length; i++) {
                let t = tagsList[i];
                if (t.name == name) {
                    tag = t;
                    return t;
                }
                if (t.children && t.children.length > 0) {
                    tag = searchTag(t.children);
                    if (tag) {
                        return tag;
                    }
                }
            }
            return false;
        }

        let tag = searchTag(vm.$store.state.app.tagsList);
        if (tag) {
            if (argu) {
                tag.argu = argu;
            }
            if (query) {
                tag.query = query;
            }
            vm.$store.commit('increateTag', tag);
        }
    }
    vm.$store.commit('setCurrentPageName', name);
};

util.searchRoute = function(routers, name) {
    let find;
    routers.forEach(r => {
        if (r.name == name) {
            find = r;
            return;
        } else {
            if (r.children && r.children.length > 0) {
                let result = util.searchRoute(r.children, name);
                if (result) {
                    find = result;
                    return;
                }
            }
        }
    });
    return find;
}

util.toDefaultPage = function (routers, name, route, next) {
    let notHandle = true;

    let find = util.searchRoute(routers, name);
    //如果点击的是目录,显示他的第一个子项目
    if (find.meta && find.meta.type == "dir" && find.children && find.children[0]) {
        route.replace({
            name: find.children[0].name
        });
        notHandle = false;
        next();
    }

    if (notHandle) {
        next();
    }
};

util.fullscreenEvent = function (vm) {
    vm.$store.commit('initCachepage');
    // 权限菜单过滤相关
    vm.$store.commit('updateMenulist');
    // 全屏相关
};

util.checkUpdate = function (vm) {
    axios.get('https://api.github.com/repos/iview/iview-admin/releases/latest').then(res => {
        let version = res.data.tag_name;
        vm.$Notice.config({
            duration: 0
        });
        if (semver.lt(packjson.version, version)) {
            vm.$Notice.info({
                title: 'iview-admin更新啦',
                desc: '<p>iView-admin更新到了' + version + '了，去看看有哪些变化吧</p><a style="font-size:13px;" href="https://github.com/iview/iview-admin/releases" target="_blank">前往github查看</a>'
            });
        }
    });
};

export default util;